package com.cpi.cornpp.instructionspurchasedetail.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.util.MessageResources;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.customer.exception.CustomerException;
import com.cpi.cornpp.customer.services.CustomerServices;
import com.cpi.cornpp.customer.view.CustomerView;
import com.cpi.cornpp.instructions.futures.services.InstructionsFuturesService;
import com.cpi.cornpp.instructions.futures.view.InstructionsFuturesView;
import com.cpi.cornpp.instructionsforecasts.exception.InstructionsForecastsException;
import com.cpi.cornpp.instructionsforecasts.service.InstructionForecastsService;
import com.cpi.cornpp.instructionsforecasts.view.InstructionsForecastsDetailView;
import com.cpi.cornpp.instructionspurchasedetail.form.InstructionPurchaseDetailForm;
import com.cpi.cornpp.instructionspurchasedetail.form.InstructionPurchaseDetailSearchForm;
import com.cpi.cornpp.instructionspurchases.exception.InstructionPurchaseException;
import com.cpi.cornpp.instructionspurchases.view.InstructionPurchaseCreateView;
import com.cpi.cornpp.period.exception.PeriodException;
import com.cpi.cornpp.product.exception.ProductException;
import com.cpi.cornpp.product.services.ProductService;
import com.cpi.cornpp.product.view.ProductView;
import com.cpi.cornpp.purchaseinstructiondetail.exception.InstructionPurchaseDetailException;
import com.cpi.cornpp.purchaseinstructiondetail.view.InstructionPurchaseDetailView;
import com.cpi.cornpp.unit.service.UnitService;
import com.cs.common.init.SystemParameterCollection;
import com.cs.common.init.beans.SystemParameterBean;
import com.cs.common.utils.NumberUtil;

public class InstructionPurchaseDetailSearchAction extends MappingDispatchAction{
	private static final String DEFAULT = "default";//$NON-NLS-1$
	private static final String FAIL = "main";//$NON-NLS-1$
	private static final String RETURN = "return";//$NON-NLS-1$
	private static final String PURCHASE_INSTRUCTION_DETAILS = "PURCHASE_INSTRUCTION_DETAILS";
	private final static String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$		
	private final static String ERROR_MESSAGE = "ERROR_MESSAGE";//$NON-NLS-1$
	private static final String MESSAGE_SELECT_A_CLIENT = "error.message.futurepurchase.add.customers";//$NON-NLS-1$
	private static final String MESSAGE_SELECT_A_PRODUCT = "error.message.futurepurchase.select.product";//$NON-NLS-1$
	private String CUSTOMER_VIEW = "CustomerView";//$NON-NLS-1$
	private String PURCHASE_INSTRUCTION_DETAIL_ID = "purchaseInstructionDetailId";//$NON-NLS-1$
	private static final String COMMENTS_LABEL = "comments";//$NON-NLS-1$
	private static final String PRESENT_LABEL = "present";//$NON-NLS-1$
	private static final String DATE_LABEL = "date";//$NON-NLS-1$
	private static final String HEADER_IN_SESSION_LABEL = "InstructionPurchaseCreateView";//$NON-NLS-1$
	private String PRODUCT_ID_PARAM = "productId";//$NON-NLS-1$
	private String CUSTOMER_ID_PARAM = "customerId";//$NON-NLS-1$
	private static final String RECORDS_TO_PURCHASES_INSTRUCTIONS_FUTURES = "RECORDS_TO_PURCHASES_INSTRUCTIONS_FUTURES";//$NON-NLS-1$
	private static final String CON_UNIT = "CON_UNIT";//$NON-NLS-1$
	private static final String CON = "CON";//$NON-NLS-1$
	private static final String PARAMETER_ID = "id";//$NON-NLS-1$
	private static final String INSTRUCTION_FORECAST_VIEWS = "InstructionsForecastsViews";//$NON-NLS-1$
	private final static String CUSTOMER_ID_LABEL = "customerId";//$NON-NLS-1$
	private static final String PARAMETER_INSTRUCTION_ID = "instructionId";//$NON-NLS-
	
	private static final String PRODUCTS_CUSTOMER_ID = "productsCustomerId";//$NON-NLS-1$1$
	private static final String CUSTOMER_PRODUCTS = "listOfProducts";//$NON-NLS-1$1$
	private static final String SELECTED_PRODUCTS = "customerSelectedProducts";//$NON-NLS-1$
	private static final String NSELECTED_PRODUCTS = "nSelectedProducts";//$NON-NLS-1$
	
	
	private SystemParameterCollection systemParameterCollection = null;
	private SystemParameterBean systemParameterBean = null;
	
	private void saveHeaderInSession(HttpServletRequest request){
		HttpSession httpSession = null;
		InstructionPurchaseCreateView instructionPurchaseCreateView = null;
		if( request.getParameter(PRESENT_LABEL) != null ){
			httpSession = request.getSession();
			instructionPurchaseCreateView = new InstructionPurchaseCreateView();
			instructionPurchaseCreateView.setDate(request.getParameter(DATE_LABEL));
			instructionPurchaseCreateView.setComments(request.getParameter(COMMENTS_LABEL));
			httpSession.setAttribute(HEADER_IN_SESSION_LABEL, instructionPurchaseCreateView);
		}
	}
	
	public ActionForward forecastByPeriod(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionsForecastsException {
		HttpSession httpSession = null;
		InstructionForecastsService instructionForecastsService = null;
		int instructionPurchaseDetailId = -1;
		int month = 0;
		int year = 0;
		String customerId = null;
		CustomerView customerView = null;
		List instructionsForecatsViews = null;
		List productViews = null;
		try{
			httpSession = request.getSession();
			instructionPurchaseDetailId = NumberUtil.getInt(request.getParameter("instructionPurchaseDetailId"));
			month = NumberUtil.getInt(request.getParameter("month"));
			year = NumberUtil.getInt(request.getParameter("year"));
			customerId = request.getParameter("customerId");
			customerView = new CustomerView();
			customerView.setCustomerId(customerId);
			instructionForecastsService = new InstructionForecastsService();
			productViews = (List)httpSession.getAttribute(SELECTED_PRODUCTS);
			instructionsForecatsViews = instructionForecastsService.list(productViews, customerView, instructionPurchaseDetailId, month, year);
			request.setAttribute("instructionsForecatsViews", instructionsForecatsViews);
		}catch(InstructionsForecastsException instructionsForecastsException){
			throw instructionsForecastsException;
		}catch(Exception exception){
			InstructionsForecastsException instructionsForecastsException = null;
			exception.printStackTrace(System.out);
			instructionsForecastsException= new InstructionsForecastsException(exception, CornPPException.LAYER_ACTION,CornPPException.ACTION_SELECT);
			httpSession.setAttribute(CUSTOM_EXCEPTION, instructionsForecastsException);
			throw instructionsForecastsException;
		}
		return mapping.findForward(DEFAULT);
	}
	
	public ActionForward deleteInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseException {
		int position = 0;
		ArrayList purchaseInstructionDetails = null;
		HttpSession httpSession = null;
		saveHeaderInSession(request);
		httpSession = request.getSession();
		position = NumberUtil.getInt(request.getParameter(PURCHASE_INSTRUCTION_DETAIL_ID));
		purchaseInstructionDetails = (ArrayList)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAILS);
		
		if(purchaseInstructionDetails!=null){
			purchaseInstructionDetails.remove(position);
		}
		
		return mapping.findForward(DEFAULT);
	}
	
	public ActionForward editInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseException, InstructionsForecastsException {
		int position = 0;
		ArrayList purchaseInstructionDetails = null;
		HttpSession httpSession = null;
		InstructionPurchaseDetailForm form = null;
		InstructionPurchaseDetailView ipdView = null;
		//InstructionForecastsService instructionForecastsService = null;
		
		saveHeaderInSession(request);
		form = (InstructionPurchaseDetailForm)actionForm;
		httpSession = request.getSession();
		String strPosition = request.getParameter(PURCHASE_INSTRUCTION_DETAIL_ID);
		if( strPosition != null){
			httpSession.setAttribute(PURCHASE_INSTRUCTION_DETAIL_ID, strPosition);
		}else{
			strPosition = (String)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAIL_ID);
		}
		position = NumberUtil.getInt(strPosition);
		purchaseInstructionDetails = (ArrayList)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAILS);
		//instructionForecastsService = new InstructionForecastsService();
		
		if(purchaseInstructionDetails!=null){
			ipdView = (InstructionPurchaseDetailView)purchaseInstructionDetails.get(position);
			//ipdView.getInstructionsForecastsDetailView().setDetails(instructionForecastsService.list((List)ipdView.getProductList(), ipdView.getCustomerView(), -1, -1, -1));
			//instructionForecastsService.markInstructionsForecastsViews(ipdView.getInstructionsForecastsDetailView().getDetails(), ipdView.getInstructionsForecastsDetailView().getChecked());
			//ipdView.setRow(String.valueOf(position));
			form.setIpdView(ipdView);
			form.setInstructionsForecastsDetailView(ipdView.getInstructionsForecastsDetailView());
			form.setInstructionsFuturesView(ipdView.getInstructionsFuturesView());
		}
		
		return mapping.findForward(DEFAULT);
	}
	public ActionForward goDirectInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseDetailException, InstructionsForecastsException, PeriodException, CustomerException {
		String productIdParam = null;
		String customerIdParam = null;
		CustomerServices customerServices = null;
		//ProductService productService = null;
		InstructionPurchaseDetailForm form = null;
		HttpSession httpSession = null;
		String messageError = null;
		MessageResources messageResources = null;
		CustomerView customerView = null;
		InstructionsFuturesService futureService = null;
		InstructionForecastsService forecastService = null;
		InstructionPurchaseDetailView ipdView = null;
		UnitService unitService = null;
		List purchaseDetails = null;
		
		InstructionsForecastsDetailView instructionsForecastsDetailView = null;
		List instructionsFuturesView = null;	
		
		httpSession = request.getSession();
		messageResources = getResources(request);
		futureService = new InstructionsFuturesService();
		forecastService = new InstructionForecastsService();
		try{
			form = (InstructionPurchaseDetailForm) actionForm;
			
			
			
			ipdView = new InstructionPurchaseDetailView();
			instructionsFuturesView = fillList(null, -1,futureService);
			
			productIdParam = request.getParameter(PRODUCT_ID_PARAM);
		
			customerIdParam = request.getParameter(CUSTOMER_ID_PARAM);
			if(productIdParam!=null && customerIdParam!=null){
				customerServices = new CustomerServices();
				//productService = new ProductService();
				form.setIpdView(ipdView);
				
				customerView = customerServices.getCustomerById(customerIdParam);				
				if( customerView == null ){
					customerView = new CustomerView();
					customerView.setCustomerId("-1");
				}
				form.getIpdView().getCustomerView().setCustomerId(customerView.getCustomerId());
				form.getIpdView().getCustomerView().setDescription(customerView.getDescription());
				
				purchaseDetails = forecastService.list((List)httpSession.getAttribute(SELECTED_PRODUCTS), customerView, -1,1,1);
				instructionsForecastsDetailView = new InstructionsForecastsDetailView();
				instructionsForecastsDetailView.setDetails(purchaseDetails);

				ipdView.setInstructionsFuturesView(instructionsFuturesView);
				ipdView.setInstructionsForecastsDetailView(instructionsForecastsDetailView);
				
				unitService = new UnitService();
				httpSession.setAttribute(CON_UNIT, String.valueOf(unitService.getUnitQuantity(CON)));
				
				ArrayList collection = (ArrayList)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAILS);
				form = (InstructionPurchaseDetailForm)actionForm;
				if(collection == null){
					collection = new ArrayList(0);
				}
				form.getIpdView().setProductList((List)httpSession.getAttribute(SELECTED_PRODUCTS));
				if( form.getIpdView().getRow() != null ){
					collection.set(NumberUtil.parseInt(form.getIpdView().getRow()), form.getIpdView());
				}else{
					collection.add(form.getIpdView());
				}
				httpSession.setAttribute(PURCHASE_INSTRUCTION_DETAILS, collection);
				
			}else{
				return mapping.findForward(FAIL);
			}
		}catch (CustomerException customerException){
				messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), customerException.getErrorCode());
				if(null == messageError){
					httpSession.setAttribute(CUSTOM_EXCEPTION, customerException);
					//form.reset(mapping, request);
					throw customerException;
				}else{
					httpSession.setAttribute(ERROR_MESSAGE, messageError);				
				}
				throw customerException;
			}
			catch (Exception e){
				CustomerException customerException=null;
				e.printStackTrace(System.out);
				customerException= new CustomerException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
				throw customerException;
			}
		
		return mapping.findForward(DEFAULT);
	}
	
	public ActionForward goInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseDetailException, InstructionsForecastsException, PeriodException {
		HttpSession httpSession = null;
		InstructionPurchaseDetailForm form = null;
		InstructionPurchaseDetailView instructionPurchaseDetailView = null;
		InstructionPurchaseDetailView ipdView = null;
		InstructionsFuturesService futureService = null;
		
		InstructionsForecastsDetailView instructionsForecastsDetailView = null;
		List instructionsFuturesView = null;	
		
		saveHeaderInSession(request);
		httpSession = request.getSession();
		
		httpSession.removeAttribute(CUSTOMER_VIEW);
		httpSession.removeAttribute(CUSTOMER_PRODUCTS);
		httpSession.removeAttribute(SELECTED_PRODUCTS);
		httpSession.removeAttribute(NSELECTED_PRODUCTS);
		httpSession.removeAttribute(PRODUCTS_CUSTOMER_ID);

		futureService = new InstructionsFuturesService();
		form = (InstructionPurchaseDetailForm)actionForm;
		
				
		instructionsFuturesView = fillList(null, -1,futureService); 		
		instructionsForecastsDetailView = new InstructionsForecastsDetailView();
		
		instructionPurchaseDetailView = new InstructionPurchaseDetailView();
		instructionPurchaseDetailView.setInstructionsFuturesView(instructionsFuturesView);
		instructionPurchaseDetailView.setInstructionsForecastsDetailView(instructionsForecastsDetailView);
		
		form.setIpdView(instructionPurchaseDetailView);
		
		ipdView = new InstructionPurchaseDetailView();
		ipdView.setInstructionsFuturesView(instructionsFuturesView);
		ipdView.setInstructionsForecastsDetailView(instructionsForecastsDetailView);		
		form.setIpdView(ipdView);
		
		
		form.setInstructionsFuturesView(instructionsFuturesView);	

		return mapping.findForward(DEFAULT);
	}
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionPurchaseDetailException
	 * @throws InstructionsForecastsException
	 * @throws PeriodException
	 */
	public ActionForward resumeInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseDetailException, InstructionsForecastsException, PeriodException {
		HttpSession httpSession = null;
		InstructionPurchaseDetailView view = null;
		InstructionPurchaseDetailForm form = null;
		CustomerView customerView = null;
		//ProductView productView = null;
		InstructionForecastsService forecastService = null;		
		InstructionsForecastsDetailView foreCastView = null;
		InstructionsFuturesService futureService = null ;
		List purchaseDetails =  null; 
		
		httpSession = request.getSession();
		saveHeaderInSession(request);
		customerView = (CustomerView)httpSession.getAttribute(CUSTOMER_VIEW);		
		form = (InstructionPurchaseDetailForm)actionForm;
		if(customerView!=null){
			view = form.getIpdView();
			view.getCustomerView().setCustomerId(customerView.getCustomerId());
			view.getCustomerView().setDescription(customerView.getDescription());
		}else{
			customerView = new CustomerView();
			customerView.setCustomerId("-1");
			view = form.getIpdView();
			view.setCustomerView(new CustomerView());
		}
		forecastService = new InstructionForecastsService();
		purchaseDetails = forecastService.list((List)httpSession.getAttribute(SELECTED_PRODUCTS), customerView, -1,-1,-1);
		foreCastView = form.getInstructionsForecastsDetailView();
		foreCastView = form.getIpdView().getInstructionsForecastsDetailView();
		foreCastView.setDetails(purchaseDetails);
		form.getIpdView().setInstructionsForecastsDetailView(new InstructionsForecastsDetailView());
		form.getIpdView().getInstructionsForecastsDetailView().setDetails(purchaseDetails);
		form.setInstructionsForecastsDetailView(foreCastView);
		forecastService.markInstructionsForecastsViews(form.getIpdView().getInstructionsForecastsDetailView().getDetails(), form.getIpdView().getInstructionsForecastsDetailView().getChecked());
		futureService = new InstructionsFuturesService();
		futureService.refreshPeriods(form.getIpdView().getInstructionsFuturesView());
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * Para uso exclusivo de agregar detalles
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionPurchaseException
	 */
	public ActionForward addInstructionPurchaseDetail(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws InstructionPurchaseException , InstructionsForecastsException, PeriodException{
		HttpSession httpSession = null; 
		InstructionPurchaseDetailForm form = null;		
		httpSession = request.getSession();
		InstructionForecastsService forecastService = null;
		InstructionsFuturesService futureService = null;
		ArrayList collection = (ArrayList)httpSession.getAttribute(PURCHASE_INSTRUCTION_DETAILS);
		form = (InstructionPurchaseDetailForm)actionForm;
		InstructionForecastsService instructionForecastsService = null;
		
		instructionForecastsService = new InstructionForecastsService();
		if(collection == null){
			collection = new ArrayList(0);
		}
		
		form.getIpdView().setProductList((List)httpSession.getAttribute(SELECTED_PRODUCTS));
		if( form.getIpdView().getRow() != null ){
			collection.set(NumberUtil.parseInt(form.getIpdView().getRow()), form.getIpdView());
		}else{
			form.getIpdView().getInstructionsForecastsDetailView().setDetails(instructionForecastsService.list((List)form.getIpdView().getProductList(), form.getIpdView().getCustomerView(), -1, -1, -1));
			collection.add(form.getIpdView());
			form.getIpdView().setRow(String.valueOf(collection.size()-1));
		}
		
		httpSession.setAttribute(PURCHASE_INSTRUCTION_DETAILS, collection);				
		forecastService = new InstructionForecastsService();
		forecastService.markInstructionsForecastsViews(form.getIpdView().getInstructionsForecastsDetailView().getDetails(), form.getIpdView().getInstructionsForecastsDetailView().getChecked());
		
		futureService = new InstructionsFuturesService();
		futureService.refreshPeriods(form.getIpdView().getInstructionsFuturesView());
		return mapping.findForward(RETURN);
	}
	
	public ActionForward searchProductAjax(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws ProductException {
		ProductService productService = null;
		ProductView productView = null;
		CustomerView customerView = null;
		String productId = null;
		String instructionId = null;
		int intIntructionId = -1;
		HttpSession httpSession = null;
		InstructionForecastsService instructionForecastsService = null;
		List instructionsForecastsViews = null;
		InstructionPurchaseDetailForm instructionPurchaseDetailForm = null;
		InstructionPurchaseDetailView instructionPurchaseDetailView = null;
		InstructionsForecastsDetailView instructionsForecastsDetailView = null;
		try{
			instructionPurchaseDetailForm = (InstructionPurchaseDetailForm)actionForm;
			instructionForecastsService = new InstructionForecastsService();
			httpSession = request.getSession();
			productId = request.getParameter(PARAMETER_ID);
			instructionId = request.getParameter(PARAMETER_INSTRUCTION_ID);
			if( instructionId != null ){
				intIntructionId = NumberUtil.parseInt(instructionId);
			}
			productService = new ProductService();
			productView = productService.getProductById(productId);
			if( productView != null ){
				instructionPurchaseDetailView = instructionPurchaseDetailForm.getIpdView();
				if( instructionPurchaseDetailView == null ){
					instructionPurchaseDetailView = new InstructionPurchaseDetailView();
					instructionPurchaseDetailForm.setIpdView(instructionPurchaseDetailView);
				}
				//instructionPurchaseDetailView.setItemId(productView.getProductId());
				//instructionPurchaseDetailView.setItemDescription(productView.getDescription());
				//TODO Setear listado de productos
				//httpSession.setAttribute(PRODUCT_VIEW, productView);
				customerView = (CustomerView)httpSession.getAttribute(CUSTOMER_VIEW);
				if( customerView != null ){
					instructionsForecastsViews = instructionForecastsService.list((List)httpSession.getAttribute(SELECTED_PRODUCTS), customerView, intIntructionId, -1, -1);
					instructionsForecastsDetailView = instructionPurchaseDetailForm.getInstructionsForecastsDetailView();
					if( instructionsForecastsDetailView == null ){
						instructionsForecastsDetailView = new InstructionsForecastsDetailView();
						instructionPurchaseDetailForm.setInstructionsForecastsDetailView(instructionsForecastsDetailView);
					}
					request.setAttribute(INSTRUCTION_FORECAST_VIEWS, instructionsForecastsViews);
					instructionsForecastsDetailView.setDetails(instructionsForecastsViews);
					instructionPurchaseDetailView.getCustomerView().setCustomerId(customerView.getCustomerId());
					instructionPurchaseDetailView.getCustomerView().setDescription(customerView.getDescription());
				}
			}else{
				//httpSession.removeAttribute(PRODUCT_VIEW);
				request.removeAttribute(INSTRUCTION_FORECAST_VIEWS);
			}
		}catch( ProductException productException ){
			throw productException;
		}catch(Exception exception){
			ProductException productException = null;
			exception.printStackTrace(System.out);
			productException= new ProductException(exception, CornPPException.LAYER_ACTION,CornPPException.ACTION_SELECT);
			httpSession.setAttribute(CUSTOM_EXCEPTION, productException);
			throw productException;
		}
		return mapping.findForward(DEFAULT);
	}

	public ActionForward searchCustomerAjax(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws CustomerException {
		CustomerServices customerServices = null;
		CustomerView customerView = null;
		String customerId = null;
		String instructionId = null;
		int intIntructionId = -1;
		HttpSession httpSession = null;
		List productViews = null;
		InstructionForecastsService instructionForecastsService = null;
		List instructionsForecastsViews = null;
		InstructionPurchaseDetailForm instructionPurchaseDetailForm = null;
		InstructionPurchaseDetailView instructionPurchaseDetailView = null;
		InstructionsForecastsDetailView instructionsForecastsDetailView = null;
		try{
			instructionPurchaseDetailForm = (InstructionPurchaseDetailForm)actionForm;
			instructionForecastsService = new InstructionForecastsService();
			httpSession = request.getSession();
			customerId = request.getParameter(PARAMETER_ID);
			instructionId = request.getParameter(PARAMETER_INSTRUCTION_ID);
			if( instructionId != null ){
				intIntructionId = NumberUtil.parseInt(instructionId);
			}
			customerServices = new CustomerServices();
			customerView = customerServices.getCustomerById(customerId);
			if( customerView != null ){
				instructionPurchaseDetailView = instructionPurchaseDetailForm.getIpdView();
				if( instructionPurchaseDetailView == null ){
					instructionPurchaseDetailView = new InstructionPurchaseDetailView();
					instructionPurchaseDetailForm.setIpdView(instructionPurchaseDetailView);
				}
				instructionPurchaseDetailView.setCustomerView(customerView);
				httpSession.setAttribute(CUSTOMER_VIEW , customerView);
				
				searchCustomerProducts(request,customerId);
				
				productViews = (List)httpSession.getAttribute(SELECTED_PRODUCTS);
				if( productViews  != null ){
					instructionsForecastsViews = instructionForecastsService.list(productViews, customerView, intIntructionId, -1, -1);
					instructionsForecastsDetailView = instructionPurchaseDetailForm.getInstructionsForecastsDetailView();
					if( instructionsForecastsDetailView == null ){
						instructionsForecastsDetailView = new InstructionsForecastsDetailView();
						instructionPurchaseDetailForm.setInstructionsForecastsDetailView(instructionsForecastsDetailView);
					}
					request.setAttribute(INSTRUCTION_FORECAST_VIEWS, instructionsForecastsViews);
					instructionsForecastsDetailView.setDetails(instructionsForecastsViews);
				}else{
					httpSession.removeAttribute(CUSTOMER_PRODUCTS);
					httpSession.removeAttribute(SELECTED_PRODUCTS);
					httpSession.removeAttribute(NSELECTED_PRODUCTS);
					httpSession.removeAttribute(PRODUCTS_CUSTOMER_ID);
				}
			}else{
				instructionPurchaseDetailView = instructionPurchaseDetailForm.getIpdView();
				if( instructionPurchaseDetailView != null ){
					instructionPurchaseDetailView.setCustomerView(new CustomerView());
				}
				httpSession.removeAttribute(CUSTOMER_PRODUCTS);
				httpSession.removeAttribute(SELECTED_PRODUCTS);
				httpSession.removeAttribute(NSELECTED_PRODUCTS);
				httpSession.removeAttribute(PRODUCTS_CUSTOMER_ID);
				httpSession.removeAttribute(CUSTOMER_VIEW);
				request.removeAttribute(INSTRUCTION_FORECAST_VIEWS);
			}
		}catch (CustomerException customerException){
			throw customerException;
		}catch (Exception exception){
			CustomerException customerException = null;
			exception.printStackTrace(System.out);
			customerException= new CustomerException(exception, CornPPException.LAYER_ACTION,CornPPException.ACTION_SELECT);
			httpSession.setAttribute(CUSTOM_EXCEPTION, customerException);
			throw customerException;
		}
		instructionPurchaseDetailForm.getIpdView().setInstructionsForecastsDetailView(instructionsForecastsDetailView);
		return mapping.findForward(DEFAULT);
	}
	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionPurchaseException
	 */
	public ActionForward searchCustomer(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws CustomerException {
		InstructionPurchaseDetailSearchForm instructionPurchaseDetailSearchForm = null;
		CustomerView customerView = null;
		String customerId = null;
		MessageResources messageResources = null;
		String messageError = null;
		HttpSession httpSession = null;
		CustomerServices customerServices = null;
		Collection listOfCustomers = null;
		try{
			listOfCustomers = new ArrayList(0);
			customerServices = new CustomerServices();
			httpSession = request.getSession();
			messageResources = getResources(request);
			instructionPurchaseDetailSearchForm = (InstructionPurchaseDetailSearchForm) actionForm;
			this.saveHeaderInSession(request);
			customerId = request.getParameter(CUSTOMER_ID_LABEL);
			customerView = new CustomerView();
			customerView.setCustomerId(StringUtils.EMPTY);
			if( StringUtils.isEmpty(customerId) ){
				customerView.setDescription(StringUtils.EMPTY);
				instructionPurchaseDetailSearchForm.setCustomerViewSearch(customerView);
			}else{
				customerView.setDescription(customerId);
				instructionPurchaseDetailSearchForm.setCustomerViewSearch(customerView);
				listOfCustomers = new ArrayList();
				listOfCustomers =  customerServices.getCustomersList(instructionPurchaseDetailSearchForm.getCustomerViewSearch());
				request.setAttribute("listOfCustomers", listOfCustomers);
				instructionPurchaseDetailSearchForm.setResultCustomerViews(listOfCustomers);
			}
		}catch (CustomerException customerException){
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), customerException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, customerException);
				instructionPurchaseDetailSearchForm.reset(mapping, request);
				throw customerException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);				
			}
			throw customerException;
		}
		catch (Exception e){
			CustomerException customerException=null;
			e.printStackTrace(System.out);
			customerException= new CustomerException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			throw customerException;
		}
		return mapping.findForward(DEFAULT);
	} 

	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws CustomerException
	 */
	public ActionForward searchCustomerResult(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws CustomerException {
		InstructionPurchaseDetailSearchForm form = null;		
		CustomerServices customerServices = null;
		Collection listOfCustomers = null;
		HttpSession httpSession = null;
		MessageResources messageResources = null;
		String messageError = null;		
		
		try{
			httpSession = request.getSession(false);
			messageResources = getResources(request);
			form = (InstructionPurchaseDetailSearchForm) actionForm;
			customerServices = new CustomerServices();
			
			listOfCustomers = new ArrayList();
			listOfCustomers =  customerServices.getCustomersList(form.getCustomerViewSearch());
			request.setAttribute("listOfCustomers", listOfCustomers);
			form.setResultCustomerViews(listOfCustomers);
			
		}catch (CustomerException customerException){
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), customerException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, customerException);
				//form.reset(mapping, request);
				throw customerException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);				
			}
			throw customerException;
		}
		catch (Exception e){
			CustomerException customerException=null;
			e.printStackTrace(System.out);
			customerException= new CustomerException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			throw customerException;
		}
		//form.reset(mapping, request);										
		return mapping.findForward(DEFAULT);	 
	}
	
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws CustomerException
	 */
	public ActionForward selectCustomer(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws CustomerException {
		
		InstructionPurchaseDetailSearchForm instructionPurchaseDetailSearchForm = null;					
		CustomerView customerView = null;					
		HttpSession httpSession = null;
		MessageResources messageResources = null;
		String messageError = null;
		String forward = null;
		
		try{
			messageResources = getResources(request);
			httpSession = request.getSession(false);
			instructionPurchaseDetailSearchForm = (InstructionPurchaseDetailSearchForm) form;
			
			if(instructionPurchaseDetailSearchForm.getCustomerViewSearch().getCustomerId() != null){								
				if (!CollectionUtils.isEmpty(instructionPurchaseDetailSearchForm.getResultCustomerViews())){
					Iterator iterator = instructionPurchaseDetailSearchForm.getResultCustomerViews().iterator();
					while (iterator.hasNext()) {
						CustomerView view = (CustomerView) iterator.next();
						if(org.apache.commons.lang.StringUtils.equals(view.getCustomerId().trim(), instructionPurchaseDetailSearchForm.getCustomerViewSearch().getCustomerId().trim())){
							customerView = new CustomerView();
							customerView.setCustomerId(view.getCustomerId());
							customerView.setDescription(view.getDescription());						
							httpSession = request.getSession(false);
							httpSession.setAttribute(CUSTOMER_VIEW , customerView);
							forward = DEFAULT;
							searchCustomerProducts(request, view.getCustomerId());
							break;
						}
					}
				}
			}else{
				messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), MESSAGE_SELECT_A_CLIENT);
				httpSession.setAttribute(ERROR_MESSAGE, messageError);
				forward = DEFAULT;
			}
						
		}catch (Exception e){
			CustomerException customerException=null;
			e.printStackTrace(System.out);
			customerException= new CustomerException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			throw customerException;
		}
		//form.reset(mapping, request);										
		return mapping.findForward(forward);
	}	
	
	
	private void searchCustomerProducts(HttpServletRequest request, String customerId) throws Exception{
		HttpSession httpSession = request.getSession();
		String currentCustomer = (String)httpSession.getAttribute(PRODUCTS_CUSTOMER_ID);
		Collection listOfProducts = null;
		ProductService productService = null;
		if(currentCustomer==null || !currentCustomer.equals(request.getParameter(CUSTOMER_ID_LABEL))){
			productService = new ProductService();
			listOfProducts =  productService.getCurrentForescastedProductList(customerId);
			httpSession.setAttribute(CUSTOMER_PRODUCTS, listOfProducts);
			httpSession.setAttribute(SELECTED_PRODUCTS, listOfProducts);
			httpSession.setAttribute(NSELECTED_PRODUCTS, new Integer(listOfProducts.size()));
			httpSession.setAttribute(PRODUCTS_CUSTOMER_ID, customerId);
		}
	}
	
	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws InstructionPurchaseException
	 */
	public ActionForward searchProducts(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws ProductException {
		InstructionPurchaseDetailSearchForm instructionPurchaseDetailSearchForm = null;
		HttpSession httpSession = null;
		try{
			httpSession = request.getSession();
			searchCustomerProducts(request,request.getParameter(CUSTOMER_ID_LABEL));
			instructionPurchaseDetailSearchForm = (InstructionPurchaseDetailSearchForm)actionForm;
			instructionPurchaseDetailSearchForm.setResultProductViews((List)httpSession.getAttribute(CUSTOMER_PRODUCTS));
			List selectedProducts = (List)httpSession.getAttribute(SELECTED_PRODUCTS);
			if(selectedProducts!=null && selectedProducts.size()>0){
				String[] idsSelectedProducts = new String[selectedProducts.size()];
				Iterator iterator = selectedProducts.iterator();
				int i=0;
				while (iterator.hasNext()) {
					ProductView product = (ProductView) iterator.next();
					idsSelectedProducts[i++]=product.getProductId();
				}
				instructionPurchaseDetailSearchForm.setSelectedProducts(idsSelectedProducts);
			}
		}catch (ProductException productException){
			MessageResources messageResources = getResources(request);
			String messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), productException.getErrorCode());
			if(null == messageError){
				httpSession.setAttribute(CUSTOM_EXCEPTION, productException);
				//instructionPurchaseDetailSearchForm.reset(mapping, request);
				throw productException;
			}else{
				httpSession.setAttribute(ERROR_MESSAGE, messageError);				
			}
			throw productException;
		}
		catch (Exception exception){
			ProductException productException=null;
			exception.printStackTrace(System.out);
			productException= new ProductException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			throw productException;
		}
		return mapping.findForward(DEFAULT);
	} 

	
	/**
	 * 
	 * @param mapping
	 * @param actionForm
	 * @param request
	 * @param response
	 * @return
	 * @throws CustomerException
	 */
	/*
	public ActionForward searchProductResult(ActionMapping mapping, ActionForm actionForm,HttpServletRequest request, HttpServletResponse response)throws ProductException {
		InstructionPurchaseDetailSearchForm form = null;
		ProductView productView = null;		
		ProductService service = null;
		List products = null;
		
		form =  (InstructionPurchaseDetailSearchForm)actionForm;
		productView = form.getProductViewSearch();
		service = new ProductService();		
		products = service.getProductList(productView);		
		form.setResultProductViews(products);
		request.setAttribute("listOfProducts", form.getResultProductViews());
		
		//form.reset(mapping, request);		
		return mapping.findForward(DEFAULT);
	}
	*/
	/**
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws CustomerException
	 */
	public ActionForward selectProduct(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws ProductException {
		InstructionPurchaseDetailSearchForm instructionPurchaseDetailSearchForm = null;		
		HttpSession httpSession = null;		
		MessageResources messageResources = null;
		
		try{
			httpSession = request.getSession(false);
			messageResources = getResources(request);
			instructionPurchaseDetailSearchForm =  (InstructionPurchaseDetailSearchForm) form;
			if( instructionPurchaseDetailSearchForm.getSelectedProducts()!=null && 
				instructionPurchaseDetailSearchForm.getSelectedProducts().length>0 &&
				instructionPurchaseDetailSearchForm.getResultProductViews()!=null
			){
				List idsSelectedProducts = new ArrayList(0);
				for(int i=0;i<instructionPurchaseDetailSearchForm.getSelectedProducts().length;i++){
					idsSelectedProducts.add((String)instructionPurchaseDetailSearchForm.getSelectedProducts()[i]);
				}
				List selectedProducts = new ArrayList(0);
				Iterator iterator = instructionPurchaseDetailSearchForm.getResultProductViews().iterator();
				while (iterator.hasNext()) {
					ProductView product = (ProductView) iterator.next();
					if(idsSelectedProducts.contains(product.getProductId())){
						selectedProducts.add(product);
					}
				}
				httpSession.setAttribute(SELECTED_PRODUCTS, selectedProducts);
				httpSession.setAttribute(NSELECTED_PRODUCTS, new Integer(selectedProducts.size()));
			}else{
				String messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), MESSAGE_SELECT_A_PRODUCT);
				httpSession.setAttribute(ERROR_MESSAGE, messageError);
			}
		}catch (Exception exception){
			ProductException productException=null;
			exception.printStackTrace(System.out);
			productException= new ProductException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			throw productException;
		}
		return mapping.findForward(DEFAULT);
		
		
		/*
		//Se verifica si el elmento seleccionado existe en la lista de productos
		listInSession = (List) httpSession.getAttribute("listOfProducts");	
		if(!StringUtils.equals(instructionPurchaseDetailSearchForm.getProductViewSearch().getProductId().trim(), StringUtils.EMPTY)){
			if(listInSession != null){
				if(!listInSession.isEmpty()){
					Iterator iterator = listInSession.iterator();
					while (iterator.hasNext()) {
						ProductView view = (ProductView) iterator.next();
						if(StringUtils.equals(view.getProductId().trim(), instructionPurchaseDetailSearchForm.getProductViewSearch().getProductId())){
							httpSession.setAttribute(PRODUCT_VIEW, view);
							forward = DEFAULT;
							break;
						}
					}			
				}
			}
		}else{
			messageError = messageResources.getMessage((Locale)httpSession.getAttribute(Globals.LOCALE_KEY), MESSAGE_SELECT_A_PRODUCT);
			httpSession.setAttribute(ERROR_MESSAGE, messageError);
			forward = DEFAULT;
		}
		
		if(!StringUtils.equals(forward, DEFAULT)){
			if (!CollectionUtils.isEmpty(instructionPurchaseDetailSearchForm.getResultProductViews())){
				Iterator iterator = instructionPurchaseDetailSearchForm.getResultProductViews().iterator();
				while (iterator.hasNext()) {
					ProductView view = (ProductView) iterator.next();
					if(org.apache.commons.lang.StringUtils.equals(view.getProductId().trim(), instructionPurchaseDetailSearchForm.getProductViewSearch().getProductId())){
						productView = new ProductView();
						productView.setProductId(view.getProductId());
						productView.setDescription(view.getDescription());
						//instructionPurchaseDetailSearchForm.setProductViewSearch(productView);
						httpSession = request.getSession(false);
						httpSession.setAttribute(PRODUCT_VIEW , productView);
						forward = DEFAULT;
						break;
					}
				}
			}
		}
		//form.reset(mapping, request);			
		return mapping.findForward(DEFAULT);
		*/
	}
	
	/**
	 * Helper Utilizado para llenar la lista
	 * de vistas InstrucionsFuturesView
	 * 
	 * @author Edgar Joao
	 * @param instructionsFuturesView
	 * @param futureService 
	 * @return
	 */
	private List fillList(List instructionsFuturesView, int purchaseInstructionDetailId, InstructionsFuturesService futureService) throws PeriodException {
		List list = null;
		list = new ArrayList(0);
		int totalRecordsToAdd = 0;
		InstructionsFuturesView iFuturesView = null;
		systemParameterCollection = SystemParameterCollection.getInstance();
		systemParameterBean = systemParameterCollection.getSystemParameterBean(RECORDS_TO_PURCHASES_INSTRUCTIONS_FUTURES);
		if(instructionsFuturesView!=null){		
			list.addAll(instructionsFuturesView);
			totalRecordsToAdd = systemParameterBean.getIntValue() - instructionsFuturesView.size();
		}else{
			totalRecordsToAdd = systemParameterBean.getIntValue();
		}
		for( int int_i = totalRecordsToAdd; int_i>0; int_i-- ){
			iFuturesView = new InstructionsFuturesView();
			iFuturesView.setPurchaseInstructionDetailId(purchaseInstructionDetailId);
			iFuturesView.setAccountPeriod(futureService.periodAccountApplication());
			iFuturesView.setApplicationPeriod(futureService.periodAccountApplication());
			list.add(iFuturesView);
		}		
		return list;
	}
	
	
}